% The function returns xoverKids—the crossover offspring—as a matrix whose 
% rows correspond to the children. The number of columns of the matrix is
% Number of variables.
function xoverKids = crossoverFnc(parents, options, nvars, FitnessFcn,...
                                  unused, thisPopulation)
% parents        — Row vector of parents chosen by the selection function
% options        — options structure
% nvars          — Number of variables
% FitnessFcn     — Fitness function
% unused         — Placeholder not used
% thisPopulation — Matrix representing the current population.
%                  The number of rows of the matrix is Population size and
%                  the number of columns is Number of variables.

nParents  = size(parents, 2);
nChildren = nParents / 2;
xoverKids = ones(nChildren, nvars);
for i = 1 : nChildren
    parent1 = i;   %randi(nParents);
    parent2 = 2*i; %randi(nParents);
    m       = randi([2 nvars-1]);

    xoverKids(i, 2:m) = thisPopulation(parents(parent1), 2:m);
    
    tmp = thisPopulation(parents(parent2), 2:end);
    for j = 2 : m
        tmp( tmp == xoverKids(i, j) ) = [];
    end
    xoverKids(i, m+1:end) = tmp;
    
%     xoverKids(i, 2:m)  = thisPopulation(parents(parent2), 2:m);
%     tmp = thisPopulation(parents(parent1), 2:end);
%     for j = 2 : m
%         tmp( tmp == xoverKids(i, j) ) = [];
%     end
%     xoverKids(i, m+1:end) = tmp;
end

end